using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using UnityEngine;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 二进制数据序列化器
    /// </summary>
    public class BinaryDataSerializer : IDataSerializer
    {
        /// <summary>
        /// 序列化对象为二进制数据（Base64编码字符串）
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>Base64编码的二进制数据字符串</returns>
        public string Serialize(object obj)
        {
            try
            {
                using var memoryStream = new MemoryStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, obj);
                return Convert.ToBase64String(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                Debug.LogError("Binary serialization failed: " + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 异步序列化对象为二进制数据（Base64编码字符串）
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>Base64编码的二进制数据字符串</returns>
        public async Task<string> SerializeAsync(object obj)
        {
            // 序列化是CPU密集型操作，使用Task.Run避免阻塞主线程
            return await Task.Run(() => Serialize(obj));
        }

        /// <summary>
        /// 从二进制数据（Base64编码字符串）反序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="data">Base64编码的二进制数据</param>
        /// <returns>反序列化的对象</returns>
        public T Deserialize<T>(string data)
        {
            try
            {
                byte[] bytes = Convert.FromBase64String(data);
                using var memoryStream = new MemoryStream(bytes);
                var formatter = new BinaryFormatter();
                return (T)formatter.Deserialize(memoryStream);
            }
            catch (Exception ex)
            {
                Debug.LogError("Binary deserialization failed: " + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 异步从二进制数据（Base64编码字符串）反序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="data">Base64编码的二进制数据</param>
        /// <returns>反序列化的对象</returns>
        public async Task<T> DeserializeAsync<T>(string data)
        {
            // 反序列化是CPU密集型操作，使用Task.Run避免阻塞主线程
            return await Task.Run(() => Deserialize<T>(data));
        }
    }
}